import { useDispatch } from 'react-redux'
import { store } from '@/store'
import { matchPath, useLocation } from 'react-router-dom'
import { useMemo } from 'react'
import { renderMenuItems } from '@/routes'
// 封装useDispatch
export const useAppDispatch = () => useDispatch<typeof store.dispatch>()

// 封装导航显示
export const useAppNavigation = () => {
    // 获取路径
    const pathname = useLocation().pathname
    // 使用useMemo缓存数据
    return useMemo(() => {
        // 获取一级导航
        const path = '/' + pathname.split('/')[1]
        const info = renderMenuItems().find((v: any) => v.path === path)
        const title = info.label
        // 获取二级导航
        let subTitle
        if (info.children) {
            // 1- 问题：不能确定浏览器请求的地址与路由地址匹配
            // const subInfo = info.children.find((v:any)=>v.path === location.pathname);

            // 2- 路由->path   /hospital/show/:id
            //    浏览器->path  /hospital/show/622574cc36a9ba1be763dad8

            //    matchPath:是一个方法，可以查看请求地址与路由地址是否匹配。第一个参数是路由设置的path,第二个参数是浏览器地址
            //              如果不匹配返回的是null,如果匹配返回的是匹配相关信息（对象）
            // console.log(matchPath("/a/b/:id","/a/b/c"))
            // console.log(matchPath("/hospital/show/:id","/hospital/show/622574cc36a9ba1be763dad8"))
            const subInfo = info.children.find((v: any) => matchPath(v.path, pathname))
            if (subInfo) subTitle = subInfo.label
        }
        return {
            title,
            subTitle
        }
    }, [pathname])
}
